import { useEffect, useRef, useState } from "react";

const BREAK_SYMBOLS = [',', '，', '.', '。', '!', '！', '?', '？', ' ', '\n'];

const cleanMarkdownText = (text: string): string => {
    return text
        // 移除代码块
        .replace(/```[\s\S]*?```/g, '')
        // 移除行内代码
        .replace(/`[^`]*`/g, '')
        // 移除标题
        .replace(/#{1,6}\s/g, '')
        // 移除粗体和斜体
        .replace(/[*_]{1,2}(.*?)[*_]{1,2}/g, '$1')
        // 移除链接
        .replace(/\[([^\]]+)\]\([^\)]+\)/g, '$1')
        // 移除图片
        .replace(/!\[([^\]]*)\]\([^\)]+\)/g, '')
        // 移除引用
        .replace(/^\s*>+\s*/gm, '')
        // 移除列表标记
        .replace(/^[\s]*[-*+]\s+/gm, '')
        // 移除数字列表
        .replace(/^\s*\d+\.\s+/gm, '')
        // 移除多余空白字符
        .replace(/\s+/g, ' ')
        .trim();
}


const useTxtAudio = () => {
    // 配置基础数据
    const audioData = useRef<{
        audioList: string[],
        lastSavedLength: number,
        audio: HTMLAudioElement[],
        close: boolean  // 关闭循环探测
        isFirstChunkSaved: boolean //
    }>({
        audioList: [],
        lastSavedLength: 0,
        audio: [],
        close: false,
        isFirstChunkSaved: false
    })

    const audioRef = useRef<HTMLAudioElement | null>(null)

    // 保存音频数据
    const saveAudioData = async () => {
        if (audioData.current.close) return
        const piece = audioData.current.audioList.shift()

        if (piece) {
            const response = await fetch('/api/tts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    text: cleanMarkdownText(piece)
                })
            });
            if (!response.ok) {
                throw new Error('语音合成请求失败');
            }
            // 获取二进制音频数据
            const audioBlob = await response.blob();

            // 创建保存音频
            const audioUrl = URL.createObjectURL(audioBlob);
            const audio = new Audio(audioUrl);
            audioData.current.audio.push(audio);
        }

        await new Promise((resolve) => setTimeout(resolve, 500));
        saveAudioData();
    }

    // 保存文本数据
    const saveAudio = (text: string) => {
        // 第一次获取约50个字符
        if (!audioData.current.isFirstChunkSaved &&
            text.length - audioData.current.lastSavedLength >= 50) {
            const targetPos = audioData.current.lastSavedLength + 50;
            const breakPos = findBreakPosition(text, audioData.current.lastSavedLength, targetPos);

            const chunk = text.slice(audioData.current.lastSavedLength, breakPos);
            audioData.current.audioList.push(chunk);
            audioData.current.lastSavedLength = breakPos;
            audioData.current.isFirstChunkSaved = true;
            return;
        }

        // 后续每次获取约200个字符
        while (text.length - audioData.current.lastSavedLength >= 300) {
            const targetPos = audioData.current.lastSavedLength + 300;
            const breakPos = findBreakPosition(text, audioData.current.lastSavedLength, targetPos);

            const chunk = text.slice(audioData.current.lastSavedLength, breakPos);
            audioData.current.audioList.push(chunk);
            audioData.current.lastSavedLength = breakPos;
        }
    };

    // 获取最后的文本数据
    const endAudio = async (text: string) => {
        console.log("endAudio", audioData.current.lastSavedLength)
        const chunk = text.slice(audioData.current.lastSavedLength, text.length);
        audioData.current.audioList.push(chunk);
    };

    // 查找最近的断句位置
    const findBreakPosition = (text: string, startPos: number, endPos: number): number => {
        for (let i = endPos; i > startPos; i--) {
            if (BREAK_SYMBOLS.includes(text[i])) {
                return i + 1;
            }
        }
        return endPos;
    };

    // 持续播放音频
    const playAudio = async () => {
        if (audioData.current.close) return

        audioRef.current = audioData.current.audio.shift() || null

        if (audioRef.current) {
            await audioRef.current.play();

            // 播放完成后释放URL
            audioRef.current.onended = () => {
                playAudio();
            };
            return;
        }

        await new Promise((resolve) => setTimeout(resolve, 500));

        playAudio();
    }

    const initAudio = () => {
        audioData.current.audioList = [];
        audioData.current.lastSavedLength = 0;
        audioData.current.audio = [];
        audioData.current.close = false;
        audioData.current.isFirstChunkSaved = false;

        if (audioRef.current) {
            audioRef.current.pause();
            audioRef.current.currentTime = 0;
            audioRef.current = null
            playAudio();
        }
    }

    // 初始化循环查看语音
    useEffect(() => {
        saveAudioData()
        playAudio()
        return () => {
            audioData.current.close = true
        }
    }, [])

    return {
        saveAudio,
        endAudio,
        playAudio,
        initAudio,
        saveAudioData
    }
}

export default useTxtAudio;